package com.sanjiahantang.youjiarole.module.city.presenters;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;


import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiarole.base.BaseMvpPresenter;
import com.sanjiahantang.youjiarole.base.CallBack;
import com.sanjiahantang.youjiarole.module.city.adapters.CityAdapter;
import com.sanjiahantang.youjiarole.module.city.beans.CityBean;
import com.sanjiahantang.youjiarole.module.city.models.ICityModel;
import com.sanjiahantang.youjiarole.module.city.models.impl.CityModel;
import com.sanjiahantang.youjiarole.module.city.views.CityView;
import com.sanjiahantang.youjiarole.module.complain.views.ComplainView;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by zy on 2017/9/19.
 */

public class CityPresenter extends BaseMvpPresenter<CityView> implements CallBack<CityBean>,CityView.OnCityClickListener,  CityView.CheckPermissionsListener {


    private ICityModel cityModel;
    private CityAdapter cityAdapter;
    private List<CityBean.City> cityList;
    private CityView.OnLoadListener onLoadListener;
    private CityView.CheckPermissionsListener permissionsListener;
    //定位
    public AMapLocationClientOption mLocationOption;
    private AMapLocationClient mLocationClient;
    public CityPresenter(){
        cityModel = new CityModel();
    }

    public void loadCityList(Context context, CityView.OnLoadListener listener) {
        mView.showProgress();
        cityList = new ArrayList<>();
        cityAdapter = new CityAdapter(context,cityList);
        cityModel.loadCityList(context,this);
        onLoadListener = listener;
        listener.initCityList(cityAdapter);
        cityAdapter.setOnCityClickListener(this);
    }

    /**
     * 初始化高德信息
     */
    private void initAMap(Context context) {
        mLocationOption = null;
        mLocationClient = mView.getAMapLocationClient();
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
//        mLocationClient.setLocationListener(this);
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setInterval(1000*60*30);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位参数
        mLocationClient.setLocationOption(mLocationOption);

        //请求权限
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
            mLocationClient.startLocation();
        }else {
            requestPermissions((Activity) context, CityView.NEEDED_PERMISSIONS, this);
        }
    }

    @Override
    public void onSuccess(CityBean response, Context context, Object tag) {
        mView.hideProgress();
        cityList.clear();
        for (CityBean.City city:response.getData().getHot_city()) {
            cityList.add(city);
        }
        cityAdapter.setCityList(cityList);
        cityAdapter.notifyDataSetChanged();
//        initAMap(context);


    }

    @Override
    public void onFailure(String message) {
        mView.hideProgress();
    }

    @Override
    public void onCityClick(CityBean.City city) {
        onLoadListener.citySelected(city);
    }

    @Override
    public void onLocateClick(Context context) {
        requestPermissions((Activity) context, CityView.NEEDED_PERMISSIONS, this);
    }

//    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                String city = aMapLocation.getCity();
                String district = aMapLocation.getDistrict();
                String location = Utils.extractLocation(city, district);
                if(cityAdapter != null){
                    cityAdapter.updateLocateState(CityView.SUCCESS, location);
                }

            } else {
                //定位失败
                if(cityAdapter != null){
                    cityAdapter.updateLocateState(CityView.FAILED, null);
                }

            }
        }
    }

    private void requestPermissions(Activity activity, String[] permissions, CityView.CheckPermissionsListener listener){
        if (activity == null) return;
        permissionsListener = listener;
        List<String> deniedPermissions = findDeniedPermissions(activity, permissions);
        if (!deniedPermissions.isEmpty()){
            ActivityCompat.requestPermissions(activity, permissions, ComplainView.REQUEST_CODE);
        }else{
            //所有权限都已经同意了
            permissionsListener.onGranted();
        }
    }

    private List<String> findDeniedPermissions(Activity activity, String... permissions){
        List<String> deniedPermissions = new ArrayList<>();
        for (String permission : permissions){
            if (ActivityCompat.checkSelfPermission(activity, permission)
                    != PackageManager.PERMISSION_GRANTED){
                deniedPermissions.add(permission);
            }
        }
        return deniedPermissions;
    }

    @Override
    public void onGranted() {
        mLocationClient.startLocation();
    }

    @Override
    public void onDenied(List<String> permissions, Context context) {
        Utils.showToast(context,"权限被禁用，请到设置里打开");
        cityAdapter.updateLocateState(CityView.FAILED, null);
    }

    public void onRequestPermissionsResult(Context context, int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case ComplainView.REQUEST_CODE:
                List<String> deniedPermissions = new ArrayList<>();
                int length = grantResults.length;
                for (int i = 0; i < length; i++){
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED){
                        //该权限被拒绝了
                        deniedPermissions.add(permissions[i]);
                    }
                }
                if (deniedPermissions.size() > 0){
                    permissionsListener.onDenied(deniedPermissions,context);
                }else{
                    permissionsListener.onGranted();
                }
                break;
            default:
                break;
        }
    }

    public int getLetterPosition(String letter) {
        if (cityAdapter == null){
            return -999;
        }
        return cityAdapter.getLetterPosition(letter);
    }
}
